﻿CREATE FUNCTION [Utilities].[SetBit]
(
	-- the bits to check as an integer
	@iBits INT
	-- this bit to test
	-- this must be a bit value
	-- e.g. 1, 2, 4, 8, 16, 32, 64, etc
	-- non bit values will produce unknown results
	-- e.g. 3, 5, 6, 7, 9, 10, 11, etc
	,@iTestBit INT
	-- should the bit be on or off
	,@iBitState BIT
)
RETURNS INT
AS
BEGIN
	DECLARE @BitState BIT;

	-- we are validating that the testbit paramater is a bit
	-- if it isn't, we return null
	IF (Utilities.IsBit(@iTestBit) = 0)
		RETURN NULL;

	-- determine the current state of the test bit
	SET @BitState = Utilities.ReadBit(@iBits, @iTestBit);

	-- leave if the value is correct
	IF (@BitState = @iBitState)
		RETURN @iBits;

	IF (@BitState = 0 AND @iBitState = 1)
		RETURN @iBits + @iTestBit;

	RETURN @iBits - @iTestBit;
END;
